package cn.wangxl.group.rpc.netclient;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

//@ChannelHandler.Sharable
public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private byte[] sendData;

    private byte[] receiveData;

    public NettyClientHandler(byte[] sendData) {
        this.sendData = sendData;
    }

    public byte[] getReceiveData() {
        return receiveData;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("echo client 接收到消息");

        int readableBytes = msg.readableBytes();
        receiveData =new byte[readableBytes];
        msg.readBytes(receiveData);

    }

    /**
     * 通道激活
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("echo client 通道激活");
        ctx.channel().writeAndFlush(Unpooled.copiedBuffer(sendData));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("echo client 捕获到异常，关闭ChannelHandlerContext");
        cause.printStackTrace();
        ctx.close();
    }
}
